package com.yequan.designpattern.singleton;

/**
 * @Auther: yq
 * @Date: 2019/1/9 16:22
 * @Description:
 */
public class StaticInnerClassSingleton {

    /**
     * 静态内部类实现单例模式(线程安全)
     * 当前方式实现的单例模式在遇到序列化对象时，得到的结果是多例的
     */
    private static class StaticInnerClassSingleTonHolder {
        private static StaticInnerClassSingleton instance=new StaticInnerClassSingleton();
    }

    private StaticInnerClassSingleton(){}

    public static StaticInnerClassSingleton getInstance(){
        try {
            Thread.sleep(300);//模仿线程耗时操作
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return StaticInnerClassSingleTonHolder.instance;
    }


    public static void main(String[] args) {
        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("thread1 >>>>> " + StaticInnerClassSingleton.getInstance().hashCode());
            }
        });
        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("thread2 >>>>> " + StaticInnerClassSingleton.getInstance().hashCode());
            }
        });
        Thread thread3 = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("thread3 >>>>> " + StaticInnerClassSingleton.getInstance().hashCode());
            }
        });

        thread1.start();
        thread2.start();
        thread3.start();
    }

}
